package com.kakame.codenews.base.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.kakame.codenews.base.constant.SystemConstant;
import com.kakame.codenews.base.util.SessionUtil;

/**
 * <pre>
 * <b>desc:</b> WebSocket链接时的拦截器 
 * <b>auth:</b> ex-hejm
 * <b>date:</b> 2018年8月9日 下午3:04:23
 * </pre>
 */
public class WebSocketInterceptor implements HandshakeInterceptor{
	
    /**
     * 与服务器websoket建立握手之前执行的方法
     */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
			Map<String, Object> attribute) throws Exception {
	    if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                //使用userId区分WebSocketHandler，以便定向发送消息
                String currentUserId = SessionUtil.getCurrentUserId(session);
                attribute.put(SystemConstant.WEBSOCKET_USERID, currentUserId);
            }
        }
        return true;
	}
		
	/**
	 * 与服务器websoket建立握手之后执行的方法
	 */
	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Exception exception) {
		
	}
 
}
